<template>
  <!-- 颜色列表 -->
  <view>
    <hx-navbar ref="hxnb" :config="config" @clickBtn="clickBtn"></hx-navbar>
    <view class="search-box flex" ref="tabBarSearch">
      <view class="input-product m-b-40">
        <u-search
          placeholder="搜索"
          bgColor="rgb(242 242 242 / 0)"
          searchIconColor="rgb(242 242 242 / 65%)"
          placeholderColor="rgb(242 242 242 / 85%)"
          v-model="searchData.keywords"
          @change="onSearchChange"
          :showAction="false"
        ></u-search>
      </view>
    </view>

    <view class="list-box flex">
      <view class="list-item" v-for="(item, index) in colorVoList" :key="index">
        <view class="t_view">
          <u-upload
            @afterRead="afterRead"
            :fileList="item.fileList"
            style="border: 1rpx solid #ddd; border-radius: 4rpx"
            :name="index.toString()"
            :maxCount="1"
            deletabl="false"
            :previewFullImage="true"
            :deletable="false"
            :multiple="false"
          >
          </u-upload>
          <view
            v-if="item.fileList.length <= 0"
            class="m-t-30"
            style="color: #ccc"
            >添加颜色图片</view
          >
        </view>
        <view class="b_con" @click="udateDetails(item, index)">
          {{ item.colorNumber }}
        </view>
        <view class="del-icon" @click="deleteColorList(index)" v-if="editShow">
          <u-icon name="close-circle-fill" color="#f00" size="18"></u-icon>
        </view>
      </view>
    </view>

    <!-- 手动添加颜色 -->
    <u-popup
      class="u-pop"
      :show="show"
      :round="10"
      mode="center"
      :closeOnClickOverlay="false"
    >
      <view class="popup-view">
        <view class="title"> 添加颜色 </view>
        <view class="form-view m-b-40">
          <view class="form-item">
            <view class="label"> 色号 </view>
            <view class="value">
              <u--input
                border="surround"
                v-model="addColorParams.colorNumber"
              ></u--input>
            </view>
          </view>
          <view class="form-item">
            <view class="label"> 颜色 </view>
            <view class="value">
              <u--input
                border="surround"
                v-model="addColorParams.color"
              ></u--input>
            </view>
          </view>
          <view class="form-item" @click="toColorSys">
            <view class="label"> 色系 </view>
            <view class="value">
              <u--input
                :disabled="true"
                disabledColor="#fff"
                border="surround"
                v-model="addColorParams.colorSystemName"
                suffixIcon="arrow-down"
                suffixIconStyle="color: #909399"
              ></u--input>
            </view>
          </view>
          <view class="form-item" @click="toConverter">
            <view class="label"> 加工商 </view>
            <view class="value">
              <u--input
                border="surround"
                :disabled="true"
                disabledColor="#fff"
                v-model="addColorParams.processorName"
                suffixIcon="arrow-down"
                suffixIconStyle="color: #909399"
              ></u--input>
            </view>
          </view>
          <view class="form-item m-t-30">
            <view class="label"> 图片 </view>
            <view class="value">
              <u-upload
                :multiple="false"
                @afterRead="addAfterRead"
                deletabl="false"
                :previewFullImage="true"
                :deletable="false"
                :maxCount="1"
                :fileList="addColorParams.fileList"
              ></u-upload>
            </view>
          </view>
        </view>
        <view class="bot-view flex flex-sa">
          <view class="btn" @click="onCencal"> 取消 </view>
          <view class="btn" @click="onConfirm"> 确认 </view>
        </view>
      </view>
    </u-popup>

    <!-- 批量添加 -->
    <u-popup
      :show="batchShow"
      :round="10"
      :closeOnClickOverlay="false"
      mode="center"
    >
      <view class="popup-view">
        <view class="title"> 批量生成 </view>
        <view class="form-view m-b-40">
          <view class="form-item">
            <view class="label"> 色号 </view>
            <view class="value flex">
              <u--input
                border="surround"
                v-model="batchParams.startNumber"
              ></u--input>
              <text class="p-r-20 p-l-20">-</text>
              <u--input
                border="surround"
                v-model="batchParams.endNumber"
              ></u--input>
            </view>
          </view>
          <view class="form-item">
            <view class="label"> 前缀 </view>
            <view class="value">
              <u--input
                border="surround"
                v-model="batchParams.prefix"
              ></u--input>
            </view>
          </view>
          <view class="form-item">
            <view class="label"> 后缀 </view>
            <view class="value">
              <u--input
                border="surround"
                v-model="batchParams.suffix"
              ></u--input>
            </view>
          </view>
          <view class="form-item" @click="toColorSys">
            <view class="label"> 色系 </view>
            <view class="value">
              <u--input
                :readonly="true"
                disabledColor="#fff"
                border="surround"
                v-model="batchParams.colorSystemName"
                suffixIcon="arrow-down"
                suffixIconStyle="color: #909399"
              ></u--input>
            </view>
          </view>
        </view>
        <view class="bot-view flex flex-sa">
          <view class="btn" @click="onBatchCencal"> 取消 </view>
          <view class="btn" @click="onBatchConfirm"> 确定 </view>
        </view>
      </view>
    </u-popup>

    <!-- 底部悬浮 -->
    <u-gap height="60" bgColor="#f5f5f5"></u-gap>
    <view class="fixed-btn flex" style="background: #fff">
      <u-button
        text="手动添加"
        shape="circle"
        style="color: rgb(64, 158, 255)"
        color="#c2e5ff"
        @click="show = true"
      ></u-button>
      <u-button
        text="批量添加"
        type="primary"
        shape="circle"
        class="m-l-20"
        @click="
          () => {
            batchShow = true;
          }
        "
        color="linear-gradient(to right, rgb(64, 158, 255), rgb(64, 158, 255), rgb(96, 180, 246), rgb(96, 180, 246))"
      ></u-button>
    </view>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import clIcon from "@/components/cl-icon/cl-icon.vue";
import { getToken } from "@/common/auth.js";
import { addOrUpdateData, updateBatch } from "@/apis/bill/goods-color";
import { addImg } from "@/apis/bill/upload-img";
export default {
  components: {
    clIcon,
  },
  data() {
    return {
      config: {
        title: "产品颜色",
        color: "#ffffff",
        //背景颜色;参数一：透明度（0-1）;参数二：背景颜色（array则为线性渐变，string为单色背景）
        backgroundColor: [1, ["#409EFF", "#409EFF", "#60b4f6", "#60b4f6"]],
        rightButton: [
          {
            key: "btn1",
            icon: "",
            txt: "编辑",
            position: "left",
          },
        ],
      },
      searchData: {},
      show: false,
      addColorParams: {
        colorNumber: "", //色号
        color: "",
        colorSystemId: "", // 色系
        colorSystemName: "", // 色系
        processorId: "", // 供应商id
        processorName: "", //供应商id
        isEnable: true,
        fileList: [],
        imageUrl: null,
        id: null,
        supId: null,
      },
      batchShow: false,
      batchParams: {
        startNumber: 1,
        endNumber: "",
        prefix: "",
        suffix: "#",
        colorSystemId: "", // 色系
        colorSystemName: "", // 色系
      },
      colorVoList: [],
      editShow: false, // 控制编辑按钮是否显示
      checkIndex: null, // 当前选中的List index
      spuId: null,
    };
  },
  // 页面周期函数--监听页面加载
  onLoad() {
    this.colorVoList = this.$getPageParams("product-information-detail").item;
    this.spuId = this.$Route.query.spuId;
    for (let i = 0; i < this.colorVoList.length; i++) {
      if (this.colorVoList[i].imageUrl != "") {
        this.colorVoList[i].fileList = [
          {
            url: this.colorVoList[i].imageUrl,
          },
        ];
      } else {
        this.colorVoList[i].fileList = [];
      }
    }
    // 颜色
    uni.$on("on-color-system-data", (data) => {
      this.addColorParams.colorSystemName = data.label;
      this.addColorParams.colorSystemId = data.value;
      this.batchParams.colorSystemName = data.label;
      this.batchParams.colorSystemId = data.value;
    });
    // 供应商
    uni.$on("on-converter-data", (data) => {
      this.addColorParams.processorId = data.id;
      this.addColorParams.processorName = data.name;
    });
  },
  methods: {
    addUpdateData() {
      if (!this.spuId) {
        return;
      }
      addOrUpdateData(this.colorVoList).then((res) => {
        if (!res.data.flag) return;
      });
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    // 列表新增图片x
    async afterRead(event) {
      const result = await this.uploadFilePromise(event.file.url);
      this.colorVoList[Number(event.name)].fileList = [
        { url: result.data.url },
      ];
      this.colorVoList[Number(event.name)].imageUrl = result.data.url;
      this.$forceUpdate();
    },
    // 手动选择新增图片
    async addAfterRead(event) {
      const result = await this.uploadFilePromise(event.file.url);
      this.addColorParams.fileList = [{ url: result.data.url }];
      this.addColorParams.imageUrl = result.data.url;
    },
    uploadFilePromise(url) {
      console.log("addImg",addImg());
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          // url: "http://localhost:8080/api/erp/oss/uploadImg", // 仅为示例，非真实的接口地址
          url: addImg(),
          filePath: url,
          name: "file",
          header: {
            Authorization: `${getToken()}`,
          },
          success: (res) => {
            resolve(JSON.parse(res.data));
          },
        });
      });
    },
    // 获取详情的颜色列表
    getInfoForBillDetailByIds() {
      getInfoForBillDetailById(this.$Route.query.data).then((res) => {
        if (!res.data.flag) return;
        const data = res.data.data || {};
        this.colorVoList = data.colorVoList;
      });
    },
    // 修改详情
    udateDetails(item, index) {
      this.checkIndex = index;
      this.addColorParams = Object.assign(this.addColorParams, item);
      this.show = true;
    },
    // 删除功能
    deleteColorList(index) {
      this.colorVoList.splice(index, 1);
    },
    // 搜索功能
    onSearchChange() {},
    // 跳转色系
    toColorSys() {
      this.$Router.push({
        name: "inventoryQuantityColorSys",
      });
    },
    // 跳转加工商
    toConverter() {
      uni.navigateTo({
        url: "/pages/application/pages/cloth/converter/index?type=list",
      });
    },
    // 取消
    onCencal() {
      this.show = false;
      this.checkIndex = null;
      this.addColorParams = {
        colorNumber: "",
        color: "",
        colorSystemId: "", // 色系
        colorSystemName: "", // 色系
        processorId: "", // 供应商id
        processorName: "", //供应商id
        isEnable: true,
        fileList: [],
        imageUrl: null,
        // id:null,
        spuId: null,
      };
      // this.$refs.swipe[this.index] && this.$refs.swipe[this.index].reset()
      this.addUpdateData();
    },
    // 确认新增
    onConfirm() {
      for (let i = 0; i < this.colorVoList.length; i++) {
        const item = this.colorVoList[i];
        if (item.colorNumber === this.addColorParams.colorNumber) {
          this.$refs.uToast.show({
            type: "error",
            title: "默认主题",
            position: "top",
            message: "色号已经存在",
            complete() {
              // uni.navigateBack()
            },
          });
          return;
        }
      }
      this.addColorParams.spuId = this.spuId;
      if (this.checkIndex == null) {
        this.colorVoList.push(JSON.parse(JSON.stringify(this.addColorParams)));
      } else {
        this.colorVoList[this.checkIndex] = Object.assign(
          this.colorVoList[this.checkIndex],
          JSON.parse(JSON.stringify(this.addColorParams))
        );
      }
      this.onCencal();
    },
    // 批量取消
    onBatchCencal() {
      this.batchShow = false;
      this.batchParams = {
        startNumber: 1,
        endNumber: "",
        prefix: "",
        suffix: "#",
        colorSystemId: "", // 色系
        colorSystemName: "", // 色系
        fileList: [],
      };
    },
    // 批量确定
    onBatchConfirm() {
      if (!this.batchParams.startNumber || !this.batchParams.endNumber) {
        this.$refs.uToast.show({
          type: "error",
          title: "默认主题",
          position: "top",
          message: "批量生产的两个范围都要填",
          complete() {
            // uni.navigateBack()
          },
        });
        return;
      }
      // 数组 2
      const array2 = [];
      for (
        let index = this.batchParams.startNumber;
        index <= this.batchParams.endNumber;
        index++
      ) {
        array2.push({
          colorNumber:
            this.batchParams.prefix + index + this.batchParams.suffix,
          colorSystemName: this.batchParams.colorSystemName,
          colorSystemId: this.batchParams.colorSystemId,
          fileList: [],
          spuId: this.spuId,
        });
      }
      // 创建一个对象来存储合并后的数据
      const mergedData = {};

      // 遍历第一个数组并将其添加到对象中
      for (const object of this.colorVoList) {
        const { colorNumber, name } = object;
        mergedData[colorNumber] = object;
      }

      // 遍历第二个数组并将其添加到对象中，但仅当 colorNumber 不存在于 mergedData 中时
      for (const object of array2) {
        const { colorNumber, name } = object;
        if (!mergedData[colorNumber]) {
          mergedData[colorNumber] = object;
        }
      }
      // 将合并后的数据转换回数组
      this.colorVoList = Object.values(mergedData);
      // this.onBatchCencal();
      const start = JSON.parse(JSON.stringify(this.batchParams.endNumber))
      this.batchShow = false;
      this.batchParams = {
        startNumber: start,
        endNumber: '',
        prefix: "",
        suffix: "#",
        colorSystemId: "", // 色系
        colorSystemName: "", // 色系
        fileList: [],
      };
    },
    clickBtn(item) {
      // console.log("index", item);
      if (item.key === "btn1") {
        this.editShow = !this.editShow;
        if (this.editShow) {
          this.config.rightButton[0].txt = "完成";
        } else {
          this.config.rightButton[0].txt = "编辑";
          // this.addUpdateData();
        }
        // this.$Router.push({
        //   path: "/pages/application/pages/information/product-information/detail/components/color-list/low-color-list-detail",
        // });
      }
    },
    scrolltolower(e) {
      // 到底了
    },
  },
  beforeDestroy() {
    uni.$emit("on-pdcl-arr", {
      type: 2,
      data: this.colorVoList,
    });
    uni.$off("on-color-data");
    uni.$off("on-converter-data");
  },
};
</script>

<style lang="scss" scoped>
.search-box {
  padding-top: 30rpx;
  justify-content: center;
  background: linear-gradient(
    to right,
    rgb(64, 158, 255),
    rgb(64, 158, 255),
    rgb(96, 180, 246),
    rgb(96, 180, 246)
  );
}
.u-upload__button {
  margin: 0 !important;
}

.input-product {
  width: 95%;
  border-radius: 50upx;
  height: 70upx;
  line-height: 70upx;
  color: #fff;
  display: flex;
  background: rgba(248, 248, 248, 0.34);
}

.ulist {
  position: absolute;
  top: 5%;
}
.u-upload__wrap {
  width: 100%;
  height: 100%;
}

.list-box {
  padding: 20rpx;
  flex-wrap: wrap;

  .list-item {
    border: 1rpx solid #ddd;
    border-radius: 8rpx;
    // overflow: hidden;
    margin-right: 8rpx;
    margin-bottom: 20rpx;
    position: relative;

    &:nth-child(3n) {
      margin-right: 0;
    }

    .del-icon {
      position: absolute;
      right: -12rpx;
      top: -12rpx;
    }

    .t_view {
      width: 225rpx;
      height: 240rpx;
      display: flex;
      flex-direction: column;
      font-size: 24rpx;
      justify-content: center;
      align-items: center;
      padding: 40rpx 30rpx;
      .u-upload {
        width: 100%;
        height: 100%;
      }

      .u-upload__wrap__preview {
        border-radius: 2px;
        margin: 0 8px 8px 0;
        position: relative;
        overflow: hidden;
        display: flex;
        flex-direction: row;
        width: 100% !important;
        height: 100% !important;
      }
    }

    .b_con {
      background-color: #fff;
      height: 48rpx;
      line-height: 48rpx;
      text-align: center;
      overflow: hidden;
    }
  }
}
</style>
